package com.guapi.controller;


import com.guapi.entity.User;
import com.guapi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    private List<User> userList;

    public void init() {
        userList = userService.getCache("userList");
    }

    public void addCache() {
        userService.setCache("userList", userList);
    }

    public void removeCache() {
        userService.deleteCache("userList");
    }


    @GetMapping("/user")
    public String getUsers(Model model) {
        //直接从缓存从获取
        init();
        if (userList == null || userList.size() == 0) {
            //缓存中没有，先设置到缓存，再从缓存中获取
            userList = userService.getAllUsers();
            addCache();
            init();
            model.addAttribute("userList", userList);
            model.addAttribute("sum", userList.size() == 0 ? 0 : userList.size());
            return "page/user";
        }
        model.addAttribute("userList", userList);
        model.addAttribute("sum", userList.size() == 0 ? 0 : userList.size());
        return "page/user";
    }

    @PostMapping("/user/insert")
    public String insert(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("sex") String sex) {
        //        首先清除缓存

        removeCache();
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setSex(sex);
        userService.insert(user);

        init();
//        重新设置缓存
        addCache();
        return "page/user";
    }

    @DeleteMapping("/user/delete/{id}")
    public String delete(@PathVariable("id") String id) {
        //        首先清除缓存
        removeCache();
        userService.delById(id);
        userList = userService.getCache("userList");
//        重新设置缓存
        addCache();
        return "page/user";
    }

    @PostMapping("/user/update")
    public String update(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("sex") String sex) {
        //        首先清除缓存
        removeCache();
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setSex(sex);
        userService.insert(user);
        init();
//        重新设置缓存
        addCache();
        return "page/user";
    }

}
